import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import styles from './Layout.less';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  Tag,
  message,
  Badge,
  Radio,
  Upload,
  Icon,
} from 'antd';

import GoodsModal from 'components/Content/GoodsModal';
import { imgPrex } from '../../utils/constData';

const FormItem = Form.Item;
const { CheckableTag } = Tag;
const Search = Input.Search;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;

@connect(({ parentRecomm, loading }) => ({
  parentRecomm,
  loading: loading.models.parentRecomm,
}))
@Form.create()
export default class LayoutDetail1 extends PureComponent {
  constructor(props) {
    super(props);

    console.log('初始化数据', this.props.layoutDetail);
    // this._queryDetailList(this.props.layoutDetail.layoutId);
    // this._setDetail(this.props.layoutDetail.detailList);

    this.state = {
      detailList: this.props.layoutDetail.detailList,
      layoutId: this.props.layoutDetail.layoutId,

      detail: (this.props.layoutDetail.detailList && this.props.layoutDetail.detailList.length > 0) ?
        this.props.layoutDetail.detailList[0] : {},
      fileList: [],

      goodsModalVisible: false,

      currentGoodsId: (this.props.layoutDetail.detailList && this.props.layoutDetail.detailList.length > 0) ?
        this.props.layoutDetail.detailList[0].goodsId : null,
      currentGoodsName: (this.props.layoutDetail.detailList && this.props.layoutDetail.detailList.length > 0) ?
        this.props.layoutDetail.detailList[0].goodsName : null,
    }
  }


  componentWillReceiveProps(nextProps) {
    if (nextProps.layoutDetail != this.props.layoutDetail) {
      this.props.form.resetFields();
      this.setState({
        detailList: nextProps.layoutDetail.detailList,
        layoutId: nextProps.layoutDetail.layoutId,
  
        detail: (nextProps.layoutDetail.detailList && nextProps.layoutDetail.detailList.length > 0) ?
          nextProps.layoutDetail.detailList[0] : {},
        fileList: [],
  
        goodsModalVisible: false,
  
        currentGoodsId: (nextProps.layoutDetail.detailList && nextProps.layoutDetail.detailList.length > 0) ?
          nextProps.layoutDetail.detailList[0].goodsId : null,
        currentGoodsName: (nextProps.layoutDetail.detailList && nextProps.layoutDetail.detailList.length > 0) ?
          nextProps.layoutDetail.detailList[0].goodsName : null,
      })
    }
  }

  componentDidMount() {

  }

  _goodsSearch(fieldsValue) {
    console.log(1111111111);
    this.props.goodsSearch(fieldsValue)
  }

  _queryDetailList() {
    this.props.dispatch({
      type: 'parentRecomm/fetchLayoutDetail',
      payload: { layoutId: this.state.layoutId },
      callback: (data) => this._setDetail(data)
    })
  }

  _setDetail(data) {
    console.log('详情返回', data);

    this.setState({ fileList: [], detail: data, })
  }


  _onRemove(type, file) {
    this.setState({ fileList: [] })
    this.props.form.setFieldsValue({ name: (this.state.detail && this.state.detail.pageImg) ? this.state.detail.pageImg : null })
  }

  normFile = (e) => {
    const isLt1M = e.file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      this.setState({ fileList: [], file: null })
      return (this.state.detail && this.state.detail.pageImg) ? this.state.detail.pageImg : null;
    }

    if (e.fileList && e.fileList.length > 0) {
      return e && e.file;
    } else {
      return null;
    }
  }

  _beforeUpload(type, file) {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('图片大小不能超过1M');
      return false;
    }

    this.setState({ fileList: [file] })

    this.props.form.setFieldsValue({ name: file });


    return false;
  }

  _setModalVisible(type, flag) {
    this._goodsSearch();
    this.setState({ goodsModalVisible: flag })
  }

  _goodsOk(type, checkedData) {
    console.log(checkedData)
    this.props.form.setFieldsValue({ goodsName: checkedData[0].goods_name })
    this.props.form.setFieldsValue({ goodsId: checkedData[0].goods_id })

    this.setState({ currentGoodsId: checkedData[0].goods_id, currentGoodsName: checkedData[0].goods_name })

    this._setModalVisible(0, false)
  }

  _saveDetail() {
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;

      let name = null;
      if (this.state.fileList && (this.state.fileList.length > 0)) {
        name = this.state.fileList[0];
      }
      let values = { ...fieldsValue, layoutId: this.state.layoutId, name: name }

      console.log(values)

      console.log('_saveDetail', values)
      if (fieldsValue.sappDetailId) {
        this.props.dispatch({
          type: 'parentRecomm/editLayoutDetail',
          payload: values,
          callback: () => {message.success('保存成功！'); this.props.recommPageSearch()}
        })
      } else {
        this.props.dispatch({
          type: 'parentRecomm/addLayoutDetail',
          payload: values,
          callback: () => {message.success('保存成功！'); this.props.recommPageSearch()}
        })
      }

    })
  }

  _cancel() {
    this.props.recommPageSearch()
  }

  render() {
    const { form, record } = this.props;
    const { detail } = this.state;
    return (
      <Card title={(this.props.layoutDetail.layoutStyle == '0') ? '编辑布局（1行1列）' : '其他'}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Form style={{ width: '65%' }}>
            {
              (this.state.fileList.length > 0) ?
                <div className={styles.layoutImage}>
                  {this.state.fileList[0].name}
                </div>
                :
                <div className={styles.layoutImage}>
                  <img
                    style={{ width: '160px', height: '160px' }}
                    src={(detail && detail.pageImg) ? (imgPrex + detail.pageImg) :
                      (this.props.layoutDetail.layoutStyle == '0') ?
                        require('../../assets/parentRecomm/pic0.png') :
                        (this.props.layoutDetail.layoutStyle == '1') ?
                          require('../../assets/parentRecomm/pic1.png') :
                          (this.props.layoutDetail.layoutStyle == '2') ?
                            require('../../assets/parentRecomm/pic2.png') :
                            require('../../assets/parentRecomm/pic0.png')
                    }
                  />
                </div>
            }
            <FormItem label="" style={{ display: 'none' }}>
              {form.getFieldDecorator('sappDetailId', {
                initialValue: detail ? detail.sappDetailId : null,
              })(
                <Input disabled={true} ></Input>
              )}
            </FormItem>
            <FormItem labelCol={{ span: 8 }} wrapperCol={{ span: 15 }} label="图片">
              {form.getFieldDecorator('name', {
                rules: [{ required: true, message: '请选择图片' }],
                initialValue: detail ? detail.pageImg : null,
                getValueFromEvent: this.normFile,
              })(
                <Upload
                  onRemove={(file) => this._onRemove(0, file)}
                  beforeUpload={(file) => this._beforeUpload(0, file)}
                  fileList={this.state.fileList}
                >
                  <Button >
                    <Icon type="upload" />选择图片
                    </Button>
                </Upload>
              )}
            </FormItem>
            <FormItem labelCol={{ span: 8 }} wrapperCol={{ span: 15 }} label="内容">
              {form.getFieldDecorator('goodsName', {
                rules: [{ required: true, message: '商品不能为空' }],
                initialValue: detail ? detail.goodsName : null,
              })(
                <span>
                  <Input disabled={true} value={this.props.form.getFieldValue('goodsName')} style={{ width: '65%' }}></Input>
                  <Button
                    onClick={() => this._setModalVisible(0, true)}
                  >选择</Button>
                </span>
              )}
            </FormItem>
            <FormItem label="" style={{ display: 'none' }}>
              {form.getFieldDecorator('goodsId', {
                initialValue: detail ? detail.goodsId : null,
              })(
                <Input disabled={true} ></Input>
              )}
            </FormItem>

            <FormItem labelCol={{ span: 8 }} wrapperCol={{ span: 15 }} label="推荐语">
              {form.getFieldDecorator('recommMsg', {
                rules: [{ required: true, message: '推荐语不能为空' }],
                initialValue: detail ? detail.recommMsg : null,
              })(
                <Input maxLength={20}></Input>
              )}
            </FormItem>

            <FormItem label="" style={{ display: 'none' }}>
              {form.getFieldDecorator('weight', {
                initialValue: detail ? detail.weight ? detail.weight : 1 : 1,
              })(
                <Input disabled={true} ></Input>
              )}
            </FormItem>

            <Button type="primary" style={{ marginLeft: '20px' }} onClick={() => this._saveDetail()}>保存</Button>
            <Button type="primary" style={{ marginLeft: '20px' }} onClick={() => this._cancel()}>取消</Button>
          </Form>

        </div>


        <GoodsModal goodsModalVisible={this.state.goodsModalVisible}
          channelTree={this.props.channelTree}
          goodsList={this.props.goodsList}
          goodsId={this.state.currentGoodsId}
          goodsName={this.state.currentGoodsName}
          setModalVisible={(type, flag) => this._setModalVisible(type, flag)}
          goodsSearch={(fieldsValue) => this._goodsSearch(fieldsValue)}
          goodsOk={(type, checkedData) => this._goodsOk(type, checkedData)}
        />
      </Card>

    );
  }
}